package com.macro.mall.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * 小红书数据解密工具
 */
public class XhsDataDecryptUtil {

    /**
     * 校验数据签名
     */
    public static boolean checkSignature(String rawData, String signature, String sessionKey) {
        String calculatedSignature = DigestUtils.sha1Hex(rawData + sessionKey);
        return calculatedSignature.equals(signature);
    }

    /**
     * 解密数据
     */
    public static String decryptData(String encryptedData, String sessionKey, String iv) throws Exception {
        byte[] sessionKeyBytes = Base64.decodeBase64(sessionKey);
        byte[] ivBytes = Base64.decodeBase64(iv);
        byte[] encryptedDataBytes = Base64.decodeBase64(encryptedData);

        SecretKeySpec keySpec = new SecretKeySpec(sessionKeyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

        byte[] decrypted = cipher.doFinal(encryptedDataBytes);
        byte[] result = PKCS7Decoder.decode(decrypted);

        return new String(result, StandardCharsets.UTF_8);
    }

    /**
     * PKCS7解码器
     */
    private static class PKCS7Decoder {
        static byte[] decode(byte[] decrypted) {
            int pad = decrypted[decrypted.length - 1];
            if (pad < 1 || pad > 32) {
                pad = 0;
            }
            return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
        }
    }
}
